<?php

namespace app\admin\controller\express;

use app\admin\model\express\OrderAddress;
use app\admin\model\express\Subscribe;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Orderpill extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\express\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\Order;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("isDeliveryList", $this->model->getIsDeliveryList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $batch_id = $this->request->param('ids','');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $batch_id = $this->request->param('batch_id','');
            $w = [];
            if($batch_id){
                $w['batch_id'] = $batch_id;
            }
            //在仓
            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                //where('order.status','complete')
                    ->where($w)->where('is_forecast','no')->whereOr(function($query){
                        $query->where('order.is_forecast','yes')->where('order.status','complete')->where('order.package_id',0);
                })->where('order.package_id',0)
                    ->order($sort, $order)
                    ->paginate($limit);

           // dump($this->model->getLastSql());
            //SELECT  user__salt,user.email AS user__email,user.mobile AS user__mobile,user.avatar AS user__avatar,user.level AS user__level,user.gender AS user__gender,user.birthday AS user__birthday,user.bio AS user__bio,user.money AS user__money,user.score AS user__score,user.successions AS user__successions,user.maxsuccessions AS user__maxsuccessions,user.prevtime AS user__prevtime,user.logintime AS user__logintime,user.loginip AS user__loginip,user.loginfailure AS user__loginfailure,user.joinip AS user__joinip,user.jointime AS user__jointime,user.createtime AS user__createtime,user.updatetime AS user__updatetime,user.token AS user__token,user.status AS user__status,user.verification AS user__verification,user.isworker AS user__isworker FROM `fa_express_order` `order` LEFT JOIN `fa_user` `user` ON `order`.`user_id`=`user`.`id` WHERE  `is_forecast` = 'no'  AND `order`.`package_id` = 0 OR (  `order`.`is_forecast` = 'yes'  AND `order`.`status` = 'complete' ) ORDER BY `order`.`id` DESC LIMIT 0,10

            foreach ($list as $row) {
                
                $row->getRelation('user')->visible(['nickname','avatar']);
                $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('batch_id',$batch_id);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $user = User::get($params['user_id']);
                    if(!$user){
                        $this->error('该用户不存在');
                    }
                    $params['order_no'] = $params['user_id'];
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $subscribe = new Subscribe();
                    $template_id = Config::get('site.new_order');
                    $page = 'pages/IndexServer/AddPackage/AddPackage?orderid='.$this->model->id;
                    $data = [
                        'character_string6' => [
                            'value' => $this->model->order_no
                        ],
                        'phrase3' => [
                            'value' => '新包裹入库'
                        ],
                        'time5' => [
                            'value' => date('Y-m-d H:i:s',time())
                        ],
                        'thing8' => [
                            'value' => '运单号:'.$this->model->from_express_no.',去完善'
                        ]
                    ];
                    $subscribe->push($params['user_id'],$template_id,$page,$data);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids,['goods']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['service'] = \app\admin\model\express\Service::where('id','in',$row['service_ids'])->select();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($params['status'] == 'waitingpay'){
                        $subscribe = new Subscribe();
                        $template_id = Config::get('site.new_order');
                        $page = 'pages/Tobepaid/Tobepaid';
                        $data = [
                            'character_string6' => [
                                'value' => $row['order_no']
                            ],
                            'phrase3' => [
                                'value' => '包裹待支付'
                            ],
                            'time5' => [
                                'value' => date('Y-m-d H:i:s',time())
                            ],
                            'thing8' => [
                                'value' => '有新的包裹待支付,支付后平台可进行发货'
                            ]
                        ];
                        $subscribe->push($row['user_id'],$template_id,$page,$data);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['address'] = OrderAddress::where('order_id',$row['id'])->find();
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 创建批次并加入批次 && 加入批次
     */
    public function addBatch(){
        if($this->request->isPost()){
            $params = $this->request->post('row/a');
            $ids = explode(',',$params['ids']);
            Db::startTrans();
            try{
                if($params['type'] == 'new'){
                    $count = model('app\admin\model\express\Batch')->whereTime('createtime','today')->count();
                    $batch  = model('app\admin\model\express\Batch')->create([
                        'batch_no' => date('Ymd').'-'.($count + 1),
                        'number' => count($ids)
                    ]);
                    $batch_id = $batch['id'];
                }else{
                    $batch_id = $params['batch_id'];
                }
                $this->model->where('id','in',$ids)->setField('batch_id',$batch_id);
                $number = $this->model->where('batch_id',$batch_id)->count();
                model('app\admin\model\express\Batch')->where('id',$batch_id)->setField('number',$number);
                Db::commit();
            }catch (PDOException $e){
                $this->error($e->getMessage());
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }

    }



    /**
     * 打印PDF
     */
    public function print($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 26);
        // 查询包裹
        $orderList = model('app\admin\model\express\Order')
            ->with(['goods'])
            ->where('id','in',$ids)
            ->select();
        // 循环包裹插入pdf
        foreach ($orderList as $order){
            $consigneeAddress = OrderAddress::get(['order_id'=>$order['id']]);
            $deliveryAddress = Db::name('express_delivery_address')->find();
            $goodsInfo = [];
            foreach ($order['goods'] as $goods){
                //$goodsInfo[] = $goods['name'].'*'.$goods['number'].'('.bcmul($goods['weight'],$goods['number'],2).$goods['unit'].')';
                $goodsInfo[] = str_replace(' ','',$goods['name'].'*'.$goods['number']);
            }
            $goodsInfoStr = implode(';',$goodsInfo);
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );
            /*$pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 15, 25, 90, 30, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/ems.png', 135, 175, 60, 20, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/check.png', 135, 253, 45, 15, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->Image(ROOT_PATH.'public/assets/img/logo.jpg', 155, 52, 32, 32, 'JPG', '', '', true, 150, '', false, false, 0, false, false, false);
            $pdf->write1DBarcode($order['express_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 10, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 10, '收件电话:'.$consigneeAddress['mobile'], 'TR', 0, 'L', 0);
            $pdf->Cell(45, 10, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'R', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '寄件人:'.$deliveryAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(90, 10, '寄件电话:'.$deliveryAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 15, '寄件地址:'.$deliveryAddress['address'], '', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '签收人', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '签收时间', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '', 'R', 0, 'C', 0);
            $pdf->Cell(45, 10, '', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '年', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '月', '', 0, 'C', 0);
            $pdf->Cell(15, 10, '日', '', 0, 'C', 0);
            $pdf->Ln();
            $pdf->Cell(90, 10, '配货信息:', 'TR', 0, 'L', 0);
            $pdf->Cell(90, 10, '重量:'.($order['delivery_weight'].'Kg'), 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 35, $goodsInfoStr, 'R', 'J', '');
            $pdf->Cell(180, 0, '', 'T', 0, 'L', 0);
            $pdf->write1DBarcode($order['express_no'], 'C128', 10, '', '', 30, 0.9, $style, '');
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件人:'.$deliveryAddress['name'], 'TR', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(90, 15, '寄件电话:'.$deliveryAddress['mobile'], 'R', 0, 'L', 0);
            $pdf->Cell(90, 15, '收件电话:'.$consigneeAddress['mobile'], '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(90, 20, '寄件地址:'.$deliveryAddress['address'], 'R', 'J', '', 0);
            $pdf->MultiCell(90, 20, '收件地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'L', 'J', '', 0);
            $pdf->Ln();
            $pdf->Cell(180, 20, '打印日期:'.date('Y-m-d'), 'TB', 0, 'L', 0);*/

            $pdf->Image(ROOT_PATH.'public/assets/img/exlogo.png', 15, 28, 80, 25, 'PNG', '', '', true, 150, '', false, false, 0, false, false, false);

            $pdf->write1DBarcode($order['order_no'], 'C128', '100', '', '', 30, 0.9, $style, 'R');
            $pdf->Ln();
            $pdf->Cell(60, 30, '收件人:'.$consigneeAddress['name'], 'T', 0, 'L', 0);
            $pdf->Cell(75, 30, '电话:'.$consigneeAddress['mobile'], 'T', 0, 'L', 0);
            $pdf->Cell(45, 30, 'ID:'.$order['user_id'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(135, 30, '地址:'.$consigneeAddress['province'].$consigneeAddress['city'].$consigneeAddress['area'].$consigneeAddress['address'], 'TR', 'L', '', 0);
            $pdf->Cell(45, 10, '秤上实重:', 'T', 0, 'C', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 40);
            $pdf->MultiCell(135, 20, '', 'R', 'L', '', 0);
            $pdf->Cell(45, 20, $order['delivery_weight'].'Kg', '', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Ln();
            $pdf->Cell(135, 10, '内件信息:', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(85, 20, $goodsInfoStr, 'R', 'J', '', 0);
            $pdf->Cell(50, 20, '提货仓代码:', 'TR', 0, 'L', 0);
            $pdf->Cell(45, 20, '', 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->cell(85, 20, '', 'R', '', '', 0);
            $pdf->SetFont('stsongstdlight', 'B', 45);
            $pdf->Cell(50, 20, 'QA', 'R', 0, 'C', 0);
            $pdf->SetFont('stsongstdlight', 'B', 26);
            $pdf->Cell(45, 20, '', '', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(30, 5, '集运单号:', 'T', 0, 'L', 0);
            $pdf->Cell(105, 5, '', 'TR', 0, 'L', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 50);
            $pdf->Cell(20, 10, '', '', 0, 'L', 0);
            $pdf->Cell(115, 10, $order['order_no'], 'R', 0, 'L', 0);

            $pdf->Cell(45, 10, '海', '', 0, 'R', 0);
            $pdf->Ln();
            $pdf->SetFont('stsongstdlight', 'B', 26);

            // ---------------------------------------------------------
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }

}
